// src/components/input.jsx
'use client';
import React, {useEffect, useRef, useState} from 'react';
import {EmojiHappyIcon, PhotographIcon, XIcon} from "@heroicons/react/outline";
import {useCurrentUser} from "@/hooks/use-current-user";
import {useGenerateUploadUrl} from "@/features/upload/api/use-generate-upload-url";
import {Avatar, AvatarFallback, AvatarImage} from "@/components/ui/avatar";
import {useCompletion} from "ai/react";
import Editor from "@/components/learn/editor";
import {useRouter} from "next/navigation";

// const Editor = dynamic(() =>
//     import('@/components/social/editor'), {ssr: false}
// );

const Input = () => {
    const router = useRouter();

    const user = useCurrentUser()
    if (!user) return <div>loading...</div>

    // 帖子内容
    const [value, setValue] = useState('')
    // 触发input传图片
    const filePickerRef = useRef(null)
    // 选中的img
    const [selectedFileBase64, setSelectedFileBase64] = useState(null)
    const [selectedFile, setSelectedFile] = useState(null)

    const [loading, setLoading] = useState(false)

    const {mutate: uploadImg, isPending} = useGenerateUploadUrl();
    const sendPost = async () => {
        if (loading) return
        setLoading(true)

        let url
        if (selectedFile) {
            url = await uploadImg({
                // @ts-ignore
                image: selectedFile,
                prefix: user?.id
            })
        }

        let post = {
            "text": value,
            "userImg": user?.image,
            // "timestamp": Date.now(),
            "timestamp": new Date(),
            "name": user?.name,
            "username": user?.name,
            // "img": selectedFileBase64,
            "userId": user?.id
        }
        if (url) post.img = url
        // json-server
        // await fetch(`${BACKEND_BATH_URL}/posts`, {
        await fetch(`/api/posts`, {
            method: 'POST',
            body: JSON.stringify(post),
            headers: {
                'Content-Type': 'application/json',
            }
        })

        setValue('')
        setSelectedFile(null)
        setSelectedFileBase64(null)
        setLoading(false)

        router.refresh()
    }

    const addImageToPost = (e) => {
        // 用于上传的img
        setSelectedFile(e.target.files[0])

        const reader = new FileReader()
        reader.onload = (readerEvent) => {
            // console.log(readerEvent.target.result)
            setSelectedFileBase64(readerEvent.target.result)
        }
        if (e.target.files[0]) {
            reader.readAsDataURL(e.target.files[0])
        } else {
            console.error('No file selected');
        }
    }

    if (!filePickerRef) return <div>loading...</div>

    // ai生成
    const {complete, completion} = useCompletion({
        // api: 'http:/localhost:3000/api/completion',
        api: '/api/completion',
    })
    const lastCompletion = useRef('')
    useEffect(() => {
        if (!completion) return
        // 新的completion(ai之前生成的sentence + ai生成的新的char) 减去 上次的completion的长度
        // 得出新的char
        const diff = completion.slice(lastCompletion.current.length);
        // 更新lastCompletion
        lastCompletion.current = completion;
        // 当前editor后面加上新char
        let newVal = value + diff
        setValue(newVal)
        // editorRef.current.insertText(editorRef.current.getSelection()?.index || 0, newVal)
    }, [completion])

    // const editorRef = useRef(null)

    return (
        <div className={'flex border-b border-gray-200 p-3 space-x-3'}>
            {/*当前登录用户头像*/}
            <Avatar className={`size-11 rounded-full`}>
                <AvatarImage className={`rounded-full`} src={user.image}/>
                <AvatarFallback className={`bg-blue-400 text-white rounded-full`}>
                    {user.name.charAt(0).toUpperCase()}
                </AvatarFallback>
            </Avatar>
            {/*<img*/}
            {/*    className={`size-11 rounded-full cursor-pointer hover:brightness-95`}*/}
            {/*    src="/logo.png" alt="logo"/>*/}
            <div className={`w-full divide-y divide-gray-200`}>
                <div className={``}>
                    {/*todo: quill or tiptap editor*/}
                    <div className={`border`}>
                        <Editor
                            value={value}
                            onChange={(richText) => setValue(richText)}
                        />
                    </div>
                    {/*<textarea*/}
                    {/*    value={value}*/}
                    {/*    onChange={(e) => setValue(e.target.value)}*/}
                    {/*    className={`p-2 w-full border-none focus:ring-0 text-lg placeholder-gray-700 tracking-wide*/}
                    {/*    min-h-[50px] text-gray-700`}*/}
                    {/*    rows="2"*/}
                    {/*    placeholder={`发送帖子或输入提示词点击AI按钮生成帖子`}*/}
                    {/*></textarea>*/}
                    {selectedFileBase64 && (
                        <div className={`relative`}>
                            <XIcon
                                onClick={() => {
                                    setSelectedFile(null)
                                    setSelectedFileBase64(null)
                                }}
                                className={`size-7 text-red-600 absolute cursor-pointer shadow-md 
                                shadow-white rounded-full`}/>
                            {/*pulse闪烁动画*/}
                            <img className={`${loading && 'animate-pulse'}`}
                                 src={selectedFileBase64}
                                 alt=""/>
                        </div>
                    )}
                </div>
                <div className={`flex items-center justify-between pt-2.5`}>
                    {!loading && (
                        <>
                            <div className={`flex`}>
                                <div onClick={() => filePickerRef.current.click()}>
                                    <PhotographIcon
                                        className={`size-10 hoverEffect p-2 text-sky-500 hover:bg-sky-100`}/>
                                    <input
                                        accept={'image/*'}
                                        type="file"
                                        hidden
                                        ref={filePickerRef}
                                        onChange={addImageToPost}
                                    />
                                </div>
                                <EmojiHappyIcon className={`size-10 hoverEffect p-2 text-sky-500 hover:bg-sky-100`}/>
                            </div>
                            <div>
                                <button
                                    onClick={() => complete(value)}
                                    disabled={!value.trim()}
                                    className={`bg-blue-400 text-white mr-2 px-4 py-1.5 rounded-full font-bold shadow-md 
                                    hover:brightness-95 disabled:opacity-50`}
                                >AI
                                </button>
                                <button
                                    onClick={sendPost}
                                    disabled={!value.trim()}
                                    className={`bg-blue-400 text-white px-4 py-1.5 rounded-full font-bold shadow-md 
                        hover:brightness-95 disabled:opacity-50`}
                                >发送
                                </button>
                            </div>
                        </>
                    )}
                </div>
            </div>
        </div>
    );
};

export default Input;